package com.hb.trade.server.project.evaluation.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hb.core.pojo.project.evaluation.dto.EvaluationCommitteeDTO;
import com.hb.core.pojo.project.evaluation.dto.EvaluationCommitteeMembersDTO;
import com.hb.core.pojo.project.evaluation.entity.EvaluationCommitteeMembers;
import com.hb.core.pojo.project.evaluation.mapper.EvaluationCommitteeBidMapper;
import com.hb.core.pojo.project.evaluation.mapper.EvaluationCommitteeMemberMapper;
import com.hb.trade.server.project.evaluation.service.EvaluationCommitteeMembersService;
import org.fzzn.core.model.enums.LogicEnum;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.util.IdUtil;
import org.fzzn.core.util.MsgUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 评标委员会成员信息 服务实现类
 * </p>
 *
 * @author ljs
 * @since 2022-1-17
 */
@Service
public class EvaluationCommitteeMembersServiceImpl extends ServiceImpl<EvaluationCommitteeMemberMapper, EvaluationCommitteeMembers> implements EvaluationCommitteeMembersService {

    @Resource
    private EvaluationCommitteeBidMapper evaluationCommitteeBidMapper;

    @Override
    public EvaluationCommitteeMembersDTO findByMemberIdCardAndPassword(String idCard, String password) {
        return baseMapper.findByMemberIdCardAndPassword(idCard, password);
    }

    @Override
    public EvaluationCommitteeMembersDTO findByMemberMobileAndPassword(String mobile, String password) {
        return baseMapper.findByMemberMobileAndPassword(mobile, password);
    }
    /**
     *
     * @Description: 查询评委会下边的评委会专家
     * @Author: zhongdl
     * @Date:2022/2/15 13:59
     * @param evaluationCommitteeId:评委会id
     * @param memberTypes: 评委会成员类别
     * @return: {@link List< EvaluationCommitteeMembersDTO> }
     **/
    @Override
    public List<EvaluationCommitteeMembersDTO> listEvaluationCommitteeMember(Long evaluationCommitteeId, List<Integer> memberTypes) {
        List<EvaluationCommitteeMembersDTO> list = CollUtil.list(false);
        //查询评委会成员
        QueryWrapper<EvaluationCommitteeMembers> wrapper = EvaluationCommitteeMembers.wrapper();
        wrapper.eq("evaluation_committee_id",evaluationCommitteeId).in(CollUtil.isNotEmpty(memberTypes),"member_type",memberTypes);
        List<EvaluationCommitteeMembers> members = list(wrapper);
        if (CollUtil.isEmpty(members)){
            return list;
        }
        //转换成子类泛型
        for (EvaluationCommitteeMembers member : members) {
            list.add(member.to(EvaluationCommitteeMembersDTO.class));
        }
        return list;
    }
    /**
     *
     * @Description: 根据得票的票数获得组长的id
     * @Author: zhongdl
     * @Date:2022/2/15 15:17
     * @param evaluationCommitteeId:
     * @return: {@link Long }
     **/
    @Override
    public Long votesCountLeaderId(Long evaluationCommitteeId) {
        return baseMapper.getVotesLeaderId(evaluationCommitteeId);
    }
    /**
     *
     * @Description: 判断评委会是否投票结束
     * @Author: zhongdl
     * @Date:2022/2/15 16:36
     * @param evaluationCommitteeId:
     * @return: {@link boolean }
     **/
    @Override
    public boolean voteEndFlag(Long evaluationCommitteeId) {

        List<EvaluationCommitteeMembersDTO> committeeMembersDTOList = listEvaluationCommitteeMember(evaluationCommitteeId, null);
        if (CollUtil.isEmpty(committeeMembersDTOList)){
            return false;
        }
        List<EvaluationCommitteeMembersDTO> collect = committeeMembersDTOList.stream().filter(committeeMembers -> committeeMembers.getLeaderId() != null && committeeMembers.getLeaderId() > 0)
                .collect(Collectors.toList());
        if (CollUtil.isEqualList(committeeMembersDTOList,collect)){
            return true;
        }
        return false;
    }

    /**
     *
     * @Description:删除评委会所有的评委会成员
     * @Author: zhongdl
     * @Date:2022/2/15 17:09
     * @param evaluationCommitteeId:
     * @return: {@link boolean }
     **/
    @Override
    public boolean removeMembersByEvaluationCommitteeId(Long evaluationCommitteeId) {
        UpdateWrapper<EvaluationCommitteeMembers> wrapper = new UpdateWrapper<>();
        wrapper.set("delete_flag", LogicEnum.YES.getCode())
                .eq("evaluation_committee_id",evaluationCommitteeId);
        return update(wrapper);
    }

    /**
    * Description: 根据标段id查询当前标段下的专家身份证号
    * @author: fengbin
    * @date: 2022/2/24 15:34
    * @param sectionId
     @return: java.util.List<java.lang.String>
    */
    @Override
    public List<String> listExpertIdCardBySectionId(Long sectionId) {
        List<String> list = baseMapper.listExpertIdCardBySectionId(sectionId);
        return list;
    }


    /**
     * 重新指定专家
     * @author tian
     * @date 2022-4-18 9:12
     * @param evaluationCommitteeDTO
     * @return org.fzzn.core.model.msg.Message<java.lang.String>
     */
    @Override
    @Transactional
    public Message<String> reassignExpert(EvaluationCommitteeDTO evaluationCommitteeDTO) {
        // 需删除的专家
        List<Long> deleteExpertIdList = evaluationCommitteeDTO.getDeleteExpertIdList();

        // 新指定的专家
        List<EvaluationCommitteeMembersDTO> expertList = evaluationCommitteeDTO.getExpertList();
        if (expertList.isEmpty() || deleteExpertIdList.isEmpty()) {
            return MsgUtil.fail("未获取到待指定的专家，请重新选择");
        }

        // 查询当前专家的类型
        EvaluationCommitteeMembers committeeMembers = baseMapper.selectById(deleteExpertIdList.get(0));

        Long leaderId = 0L;
        // 如果是组长 需要将选举组长的信息清空
        if (committeeMembers.getChairmanFlag().equals(1)) {
            baseMapper.updateLeaderIdByEvaluationCommitteeId(evaluationCommitteeDTO.getId());
        } else {
            // 如果不是组长 需要将组长的id同步至新指定的专家
            leaderId = committeeMembers.getLeaderId();
        }

        for (EvaluationCommitteeMembersDTO evaluationCommitteeMembersDTO : expertList) {
            EvaluationCommitteeMembers evaluationCommitteeMembers = new EvaluationCommitteeMembers();
            evaluationCommitteeMembersDTO.to(evaluationCommitteeMembers);

            evaluationCommitteeMembers.setEvaluationCommitteeId(evaluationCommitteeDTO.getId());
            evaluationCommitteeMembers.setMemberId(evaluationCommitteeMembersDTO.getMemberId());
            evaluationCommitteeMembers.setPassword(randomPassword());
            evaluationCommitteeMembers.setCreateId(evaluationCommitteeDTO.getCreateId());
            evaluationCommitteeMembers.setCreateName(evaluationCommitteeDTO.getCreateName());
            evaluationCommitteeMembers.setCreateTime(LocalDateTime.now());
            evaluationCommitteeMembers.setMemberType(committeeMembers.getMemberType());
            evaluationCommitteeMembers.setExtractType(1);

            if (null != leaderId && leaderId != 0) {
                evaluationCommitteeMembers.setLeaderId(leaderId);
            }
            // 这里的id是专家id 需要重新设置
            evaluationCommitteeMembers.setId(IdUtil.getId());
            baseMapper.insert(evaluationCommitteeMembers);
        }

        baseMapper.deleteBatchIds(deleteExpertIdList);
        return MsgUtil.success();
    }



    /**
     * 重新指定组长
     * @author tian
     * @date 2022-4-18 9:11
     * @param evaluationCommitteeDTO
     * @return org.fzzn.core.model.msg.Message<java.lang.String>
     */
    @Override
    public Message<String> reassignLeaderExpert(EvaluationCommitteeDTO evaluationCommitteeDTO) {
        // 查询组长id是否存在
        QueryWrapper<EvaluationCommitteeMembers> wrapper = EvaluationCommitteeMembers.wrapper();
        wrapper.eq("evaluation_committee_id",evaluationCommitteeDTO.getId())
                .eq("id",evaluationCommitteeDTO.getLeaderId());
        List<EvaluationCommitteeMembers> members = list(wrapper);
        if (CollUtil.isEmpty(members)){
            return MsgUtil.fail("未查询到组长的信息");
        }

        // 修改全部专家的投标组长id，并且先将是否组长标识设置为否
        UpdateWrapper<EvaluationCommitteeMembers> updateWrapper1 = new UpdateWrapper<>();
        updateWrapper1.set("leader_id", evaluationCommitteeDTO.getLeaderId())
                .set("chairman_flag", 0)
                .eq("evaluation_committee_id",evaluationCommitteeDTO.getId());
        update(updateWrapper1);


        // 修改当前专家为组长
        UpdateWrapper<EvaluationCommitteeMembers> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("chairman_flag", 1)
                .eq("id",evaluationCommitteeDTO.getLeaderId());
        update(updateWrapper);

        return MsgUtil.success();
    }

    @Override
    public List<EvaluationCommitteeMembers> selectCommitteeMembersBySectionId(Long sectionId, String chairmanFlag) {
        return evaluationCommitteeBidMapper.selectCommitteeMembersBySectionId(sectionId, chairmanFlag);
    }

    @Override
    public Boolean evaluationStarted(Long evaluationCommitteeId) {
        QueryWrapper<EvaluationCommitteeMembers> wrapper = new QueryWrapper<>();
        wrapper.eq("evaluation_committee_id", evaluationCommitteeId).
                isNotNull("leader_id").
                eq("confirmation_flag", 1);
        Long count = baseMapper.selectCount(wrapper);
        if (count > 0) {
            return true;
        }

        return false;
    }

    /**
     * 查评委会会专家信息
     *
     * @author tian
     * @date 2022-6-18 14:37
     * @param evaluationCommitteeMembers
     * @return java.util.List<com.hb.core.pojo.project.evaluation.entity.EvaluationCommitteeMembers>
     */
    @Override
    public List<EvaluationCommitteeMembers> selectInfoByEvaluationCommitteeIdAndMemberType(EvaluationCommitteeMembers evaluationCommitteeMembers) {
        return baseMapper.selectInfoByEvaluationCommitteeIdAndMemberType(evaluationCommitteeMembers);
    }


    /**
     * 生成随机的六位数密码（整形）
     *
     * @return
     */
    public String randomPassword() {
        String randomNum = "";
        for (int i = 0; i < 6; i++){
            String num = RandomUtil.randomInt(10) + "";
            randomNum += num;
        }
        return randomNum;
    }

    @Override
    public List<EvaluationCommitteeMembers> findBySectionId(Long sectionId) {
        List<EvaluationCommitteeMembers> evaluationCommitteeMembersList = baseMapper.findBySectionId(sectionId);
        return evaluationCommitteeMembersList;
    }




}
